package com.mfhcd.facepay.activity

import android.os.Bundle
import android.text.TextUtils
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.jakewharton.rxbinding3.view.clicks
import com.mfhcd.facepay.R
import com.mfhcd.facepay.base.BaseActivity
import com.mfhcd.facepay.constant.ArouterUrl
import com.mfhcd.facepay.databinding.ActivityTestBinding
import com.mfhcd.facepay.model.ResponseModel
import com.mfhcd.facepay.model.TitleBean
import com.mfhcd.facepay.utils.Constants
import com.mfhcd.facepay.utils.PhotoUtil
import com.mfhcd.facepay.utils.ToastUtil
import com.mfhcd.facepay.viewmodel.TestViewModel
import java.util.concurrent.TimeUnit

@Route(path = ArouterUrl.ACTIVITY_TEST)
class TestActivity : BaseActivity<TestViewModel, ActivityTestBinding>() {

    @Autowired(name = Constants.MERCHANT_NO)
    lateinit var merNo: String

    @Autowired
    lateinit var APP: String

    @JvmField
    @Autowired(name = "testStatus")
    var testStatus: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        mBaseBinding.titleBean = TitleBean("测试")
    }

    override fun initData() {
        bindingView.merchantNo = merNo
        bindingView.status = testStatus
        bindingView.test = APP
        getImageCode()
    }

    override fun initListener() {
        bindingView.ivImageCode.clicks()
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe { getImageCode() }
    }

    private fun getImageCode() {
        viewModel.test().observe(this, Observer { resp: ResponseModel.TestResp -> this.onRefreshImCode(resp) })
    }

    private fun onRefreshImCode(resp: ResponseModel.TestResp) {
        if (!TextUtils.isEmpty(resp.captchaImg)) {
            val imgSplit = resp.captchaImg.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            if (imgSplit.size >= 2) {
                val base64Img = imgSplit[1]
                val img = PhotoUtil.decodeBase64Image(base64Img)
                bindingView.ivImageCode.setImageBitmap(img)
            } else {
                ToastUtil.showToast("图形验证码获取失败")
            }
        } else {
            ToastUtil.showToast("图形验证码获取失败")
        }

    }



}
